package database;
import java.sql.ResultSet;
import java.sql.SQLException;

import main.Terminal;
import model.Employee;

public class DBEmployee {
	
	private DBConnection con;
	
	public DBEmployee()
	{
		con = DBConnection.getInstance();
	}
	
	public void createEmployee(Employee emp)
	{
		String empPass = emp.getPassword();
		String empName = emp.getName();
		String empPhone = emp.getPhone();
		String query = String.format("Insert INTO employee Values ('%s', '%s', '%s')", 
				empPass, empName,  empPhone);
		con.execute(query);
	}
	
	public Employee getEmployee(String phone)
	{
		Employee result = null;
		String condition = String.format("Select password, name, phone from Employee where phone = '%s'", phone);
		ResultSet resSet = con.executeResSet(condition);
		try {
			if(resSet.next()) {		
				result = buildEmployee(resSet);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public Employee getEmployeeFromPass(String password)
	{
		Employee result = null;
		String condition = String.format("Select password, name, phone from Employee where password = '%s'", password);
		ResultSet resSet = con.executeResSet(condition);
		try {
			if(resSet.next()) {
				result = buildEmployee(resSet);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	private Employee buildEmployee(ResultSet resSet)
	{
		Employee result = null;
		try{
			String name = resSet.getString("Name");
			String password = resSet.getString("Password");
			String phoneNum = resSet.getString("Phone");
			result = new Employee(password, name, phoneNum);
			resSet.getStatement().close();
		}
		catch(SQLException e){
			Terminal.say("could not build emp", e);
		}
		catch(Exception e)
		{
			Terminal.say("could not build emp", e);
		}
		return result;
	}
	
	
}
